import MarkdownIt from 'markdown-it'
import DOMPurify from 'dompurify'
import hljs from 'highlight.js'

const md = new MarkdownIt({
  html: false,
  linkify: true,
  breaks: true,
  highlight: function (code, lang) {
    try {
      if (lang && hljs.getLanguage(lang)) {
        const out = hljs.highlight(code, { language: lang }).value
        return `<pre><code class="hljs language-${lang}">${out}</code></pre>`
      }
      const out = hljs.highlightAuto(code).value
      return `<pre><code class="hljs">${out}</code></pre>`
    } catch (e) {
      return `<pre><code class="hljs">${code}</code></pre>`
    }
  }
})

export function renderMarkdown(text) {
  const source = typeof text === 'string' ? text : (text ?? '')
  const html = md.render(source)
  const clean = DOMPurify.sanitize(html, {
    ALLOWED_ATTR: ['class', 'href', 'target', 'rel', 'src', 'alt', 'title']
  })
  return clean
} 